package com.ckjava.test.service;

import com.ckjava.test.dao.BaseCrudDao;
import com.ckjava.test.entity.BaseEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Transactional(readOnly = true)
public abstract class BaseCrudService<D extends BaseCrudDao<T>, T extends BaseEntity> {

	@Autowired
	private D d;

	/**
	 * 插入数据
	 * @param t
	 * @return
	 */
	@Transactional
	public Long insert(T t) {
		d.insert(t);
		return t.getId();
	}

	/**
	 * 分页查询
	 * @param t
	 * @return
	 */
	public List<T> getPage(T t) {
		return d.getPage(t);
	}

	/**
	 * 获取分页查询条件的记录总数
	 * @param t
	 * @return
	 */
	public Integer getCount(T t) {
		return d.getCount(t);
	}

	/**
	 * 点击列表中的记录 获取单个 T
	 * @param id
	 * @return Long
	 */
	public T get(Long id) {
		return d.get(id);
	}

    /**
     * 修改或者保存
     * @param t
     * @return
     * @throws Exception
     */
    @Transactional
    public Long saveOrUpdate(T t) throws Exception {
        if (t.getId() != null) { // 更新
            t.setUpdateDate(new Date());
            t.setUpdateUser(t.getUpdateUser());
        } else {
            t.setDelFlag("0");
            t.setCreateDate(new Date());
            t.setCreateUser(t.getCreateUser());
        }

        if (t.getId() != null) { // 更新
            d.update(t);
        } else { // 新增
            d.insert(t);
        }

        return t.getId();
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @Transactional
    public Integer delete(Long id) {
        return d.delete(id);
    }
}